using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
using System.Diagnostics;
using Unity.VisualScripting;
using System.Collections;
public class GameUIControl : MonoBehaviour
{
    public event System.Action<int> OnDieChanged; // 任意场景都可订阅

    public TextMeshProUGUI Source;
    public GameObject LoseGameOver;
    public GameObject PauseGameOver;
    public GameObject SettingsPrefab;
    public Canvas GUICanvas;
    public GameObject GameOver;
    public GameObject BagUIPage;

    public float duration = 0.3f; // 动画时长
    void OnEnable()
    {
        if (GameManager.Instance != null)
            GameManager.Instance.OnScoreChanged += UpdateScore;
    }
    void Start()
    {
        Source.text = $"{GameManager.Instance.Score}";
        LoseGameOver.SetActive(false);
        PauseGameOver.SetActive(false);
        GameOver.SetActive(false);

    }
    void OnDisable()
    {
        if (GameManager.Instance != null)
            GameManager.Instance.OnScoreChanged -= UpdateScore;
    }

    // Update is called once per frame
    void UpdateScore(int newScore)
    {
        Source.text = $"{newScore}";
    }


    //返回主菜单
    public void BackHome()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene("mainScene");
    }
    //重玩
    public void ReplayGame()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
    //继续游戏
    public void ContinueGame()
    {
        Time.timeScale = 1f;
        PlayScaleOpenUI(false, PauseGameOver);
    }
    //暂停游戏
    public void PauseGame()
    {
        // Time.timeScale = 0.1f;
        // PauseGameOver.interactable = true;
        PlayScaleOpenUI(true, PauseGameOver);
    }

    //下一关
    public void NextGame()
    {
        Time.timeScale = 1f;
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }


    //游戏结束
    public void viewGameOverMenu(bool gameOver)
    {
        if (gameOver)
        {
            //打开游戏成功弹窗
            PlayScaleOpenUI(true, GameOver);
            return;
        }
        // 打开失败弹窗
        PlayScaleOpenUI(true, LoseGameOver);
    }
    void viewGamePauseMenu()
    {
        // 打开菜单
        PlayScaleOpenUI(true, PauseGameOver);
    }

    public void OpenSettingsUI()
    {
        GameObject instance = Instantiate(SettingsPrefab, transform.position, Quaternion.identity, GUICanvas.transform);
        instance.transform.SetParent(GUICanvas.transform);
    }

    public void OpenBag()
    {
        PlayScaleOpenUI(true, BagUIPage);
    }
    public void CloseBag()
    {
        PlayScaleOpenUI(false, BagUIPage);
    }
    public void PlayScaleOpenUI(bool isOpen, GameObject Node)
    {
        StopAllCoroutines();                     // 防止多次叠加
        StartCoroutine(UIAnimations.ScaleAnimRoutine(Node.transform, isOpen, duration));
    }

}
